﻿namespace PAR.Audio
{
    using System;
    using System.Windows;
    using Microsoft.Phone.Controls;

    public partial class Recorder : PhoneApplicationPage
    {
        AudioGraph _graph;
        PolygonWaveForm waveform;

        DateTime _startDateTime;

        public Recorder()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            string mode = string.Empty;

            if (!NavigationContext.QueryString.TryGetValue("mode", out mode))
            {
                mode = "WaveForm";
            }

            _graph = new AudioGraph();

            if (mode == "Incognito")
            {
                LayoutRoot.Children.Clear();
                LayoutRoot.Children.Add(new LockScreen());
            }
            else
            {
                waveform = new PolygonWaveForm();
                LayoutRoot.Children.Clear();
                LayoutRoot.Children.Add(waveform);
                _graph.MaximumCalculated += new EventHandler<MaxSampleEventArgs>(_graph_MaximumCalculated);
            }

            _graph.Start();
            _startDateTime = DateTime.Now;
        }

        void _graph_MaximumCalculated(object sender, MaxSampleEventArgs e)
        {
            if (waveform != null)
            {
                waveform.AddValue(e.MaxSample, e.MinSample);
            }
        }

        string FileNameFromDateTime(DateTime dt)
        {
            return dt.ToString("ddMMyyyy_hhmmss.wav");
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            _graph.Stop(FileNameFromDateTime(_startDateTime));
            _graph.MaximumCalculated -= _graph_MaximumCalculated;

            _graph = null;

            if (waveform != null)
            {
                waveform.Reset();
            }
            LayoutRoot.Children.Clear();
            waveform = null;
        }
    }
}